package pl.uz.zgora.plan;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

public class SettingsViewActivity extends Activity {
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.settings_menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.advanced_settings:
	            showAdvancedSettings();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	private void showAdvancedSettings() {
		Intent intent = new Intent(this, AdvancedSettingsActivity.class);
		startActivity(intent);
	}

	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.settings_view);
	    
	    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
	            this, R.array.frequences_array, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    
	    final Spinner autoUpdateFreqSpinner = (Spinner) findViewById(R.id.settings_auto_update_frequency);
	    autoUpdateFreqSpinner.setAdapter(adapter);
	    final int selectedFreq = PrefrencesManager.getInstance(this).getIntFromPreferences("auto_update_frequency");
	    if(selectedFreq > 0) {
	    	autoUpdateFreqSpinner.setSelection(selectedFreq);
	    } else { autoUpdateFreqSpinner.setSelection(0); }
	    autoUpdateFreqSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				final PrefrencesManager pm = PrefrencesManager.getInstance(view.getContext());
				// get a Calendar object with current time
				Calendar cal = Calendar.getInstance();
				final Intent intent = new Intent(parent.getContext(), AutoUpdateWebserviceReciever.class);
				// In reality, you would want to have a static variable for
				// the request code instead of 192837
				final PendingIntent operation = PendingIntent.getBroadcast(view.getContext(),
						192837, intent, PendingIntent.FLAG_UPDATE_CURRENT);
				// Get the AlarmManager service
				final AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
				long interval = 0;
				switch (pos) {
				case 0: {
					am.cancel(operation);
					pm.addIntToPreferences("auto_update_frequency", 0);
				}
					break;
				case 1: {
					cal.add(Calendar.DAY_OF_YEAR, 1);
					
					interval = AlarmManager.INTERVAL_DAY;
					am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), interval, operation);
					pm.addIntToPreferences("auto_update_frequency", 1);
					
				}
					break;
				case 2: {
					cal.add(Calendar.DAY_OF_YEAR, 7);
					
					interval = AlarmManager.INTERVAL_DAY * 7;
					
					am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), interval, operation);
					pm.addIntToPreferences("auto_update_frequency", 2);
					
				}
					break;
				case 3: {
					cal.add(Calendar.DAY_OF_YEAR, 14);
					
					interval = AlarmManager.INTERVAL_DAY * 14;
					am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), interval, operation);
					pm.addIntToPreferences("auto_update_frequency", 3);
					
				}
					break;
				case 4: {
					cal.add(Calendar.DAY_OF_YEAR, 30);
					
					interval = AlarmManager.INTERVAL_DAY * 30;
					am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), interval, operation);
					pm.addIntToPreferences("auto_update_frequency", 4);
					
				}
					break;

				default:
					break;
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {}
		});
	    
	    final Button btnRefresh = (Button) findViewById(R.id.refreshButton);
	    btnRefresh.setOnClickListener(new OnClickListener() {
			
			public void onClick(View view) {
				if (HelperMethodsManager.isOnline(view.getContext())) {
					
					final Intent intent = new Intent(view.getContext(),
							MainMenuActivity.class);
					
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					
					final PlanUzDataSource planDataSource = new PlanUzDataSource(
							view.getContext());
					
					final Plan plan = planDataSource.readPlan();
					
					final String appMode = PrefrencesManager.getInstance(
							view.getContext()).getStringFromPreferences(
							"appmode");
					
					if (appMode.equals("teacher")) {
						// Tryb nauczyciel
						if(plan.getNauczycieli() != null) {
							final Nauczyciel nauczyciel = plan.getNauczycieli()
									.get(0);

							intent.putExtra("idNauczyciela",
									nauczyciel.getIdNauczyciela());
							intent.putExtra("nazwaNauczyciela",
									nauczyciel.getNazwa());

							startActivity(intent);
						}
					} else if (appMode.equals("student")) {
						// Tryb student
						final Grupa grupa = plan.getGroup();
						if(grupa != null) {
							intent.putExtra("idGrupy", grupa.getIdGrupy());
							intent.putExtra("nazwaGrupy", grupa.getNazwa());

							startActivity(intent);
						}
					}
				} else {
					Dialog errorDialog = HelperMethodsManager.getConnectionErrorDialog(view.getContext(), SettingsViewActivity.this);
			    	errorDialog.show();
				}
			}
		});
	    
	    final Spinner notifyDelaySpinner = (Spinner) findViewById(R.id.settings_notify_delay);
	    final int selectedDelay = PrefrencesManager.getInstance(this).getIntFromPreferences("notify_delay");
	    if(selectedDelay > 0) {
	    		notifyDelaySpinner.setSelection(selectedDelay);
	    } else {
	    	notifyDelaySpinner.setSelection(0);
	    }
	    notifyDelaySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

	    	final Intent intent = new Intent(SettingsViewActivity.this, NotifyService.class);
	    	
	    	public void onItemSelected(AdapterView<?> parent, View view,
	    			int pos, long id) {
	    		final PrefrencesManager pm = PrefrencesManager.getInstance(view.getContext());
	    		switch (pos) {
		    		case 0: {
		    			stopService(intent);
		    			pm.addIntToPreferences("notify_delay", 0);
		    		}
		    		break;
		    		
		    		case 1: {
		    			stopService(intent);
		    			NotifyService.setNotifyDelay(5);
		    			startService(intent);
		    			pm.addIntToPreferences("notify_delay", 1);
		    		}
		    		break;
		    		
		    		case 2: {
		    			stopService(intent);
		    			NotifyService.setNotifyDelay(10);
		    			startService(intent);
		    			pm.addIntToPreferences("notify_delay", 2);
		    		}
		    		break;
		    		
		    		case 3: {
		    			stopService(intent);
		    			NotifyService.setNotifyDelay(15);
		    			startService(intent);
		    			pm.addIntToPreferences("notify_delay", 3);
		    		}
		    		
		    		case 4: {
		    			stopService(intent);
		    			NotifyService.setNotifyDelay(30);
		    			startService(intent);
		    			pm.addIntToPreferences("notify_delay", 4);
		    		}
		    		break;
		    		
		    		case 5: {
		    			stopService(intent);
		    			NotifyService.setNotifyDelay(45);
		    			startService(intent);
		    			pm.addIntToPreferences("notify_delay", 5);
		    		}
		    		break;
	    		}
	    	}

			public void onNothingSelected(AdapterView<?> arg0) {}
		});
	    
	    final Button btnEditData = (Button) findViewById(R.id.editData);
	    btnEditData.setOnClickListener(new OnClickListener() {

	    	public void onClick(View v) {
	    		if (HelperMethodsManager.isOnline(v.getContext())) {
	    			final Intent intent = new Intent(v.getContext(), StartPageActivity.class);
	    			intent.putExtra("forceDBDelete", true);

	    			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

	    			PrefrencesManager pm =  PrefrencesManager.getInstance(v.getContext());
	    			pm.addBooleanToPreferences("hasData", false);
	    			
	    			startActivity(intent);
	    			setResult(100);
	    			finish();
	    		} else {
	    			Dialog errorDialog = HelperMethodsManager.getConnectionErrorDialog(v.getContext(), SettingsViewActivity.this);
	    	    	errorDialog.show();
	    		}
	    	}
	    });
	    
	    

	}
}
